// 接口请求异常的处理
import Vue from 'vue'
import axios from 'axios'
import { Message } from 'element-ui'
// import { setToken } from './localPul'
import router from '@/router'
// export const BASE_API = IPCONFIG
// export const BASE_URL = IPCONFIG_BASEURL
// 此为反向代理地址
// export const BASE_API = 'https://znyd.cevmp.cn:8843';
// export const BASE_URL = 'https://znyd.cevmp.cn:8000/file/excel_template';

// export const BASE_API = 'https://chuangyuan.cevmp.cn/gateway';// 绿动
// export const BASE_URL = 'https://chuangyuan.cevmp.cn/minio/excel_template';// 绿动

// export const BASE_API = 'https://cevrc.cevmp.cn/gateway';  //
// export const BASE_URL = 'https://cevrc.cevmp.cn:8080/file/excel_template';  //

// export const BASE_API = 'https://www.cyc0519.com/gateway';  //常州
// export const BASE_URL = 'https://www.cyc0519.com/minio/excel_template';  //常州


//
// export const BASE_API = 'http://192.168.0.52:8843';
// export const BASE_URL = 'http://192.168.0.51:9000/excel_template';

export const BASE_API = '' //生产环境
export const BASE_URL = 'http://20.46.35.26:8081'; //生产环境
export const BASE_URL_CAREVAL = 'http://20.46.35.26:31136/gateway/careval' //生产环境

let downloadLoadingInstance;
//export const BASE_API = IPCONFIG
//export const BASE_URL = IPCONFIG_BASEURL;
// 资料 系统管理  报表之
var otime = null;
var otime_s = 0;
var otime_ = setInterval(function () {
  if (otime_s) {
    Message({
      message: '登录已过期或已有新用户登录,请重新登陆',
      type: 'error',
    });
  }
}, 200)
let refreshTokenFlag = false;
let requestList = [];
function executeRequests(index) {
  if (index < requestList.length) {
    requestList[index]().then(() => {
      executeRequests(index + 1)
    })
  } else {
    refreshTokenFlag = false
    requestList.splice(0, requestList.length)
  }
}

const service = axios.create({
  baseURL: (process.env.NODE_ENV === 'production' ? process.env.BASE_API : BASE_API),
  timeout: 120000, // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    let token = JSON.parse(window.sessionStorage.getItem('user'))//无token
    // let token = Vue.cookie.get('token');
    if (token) {
      config.headers['Authorization'] = "Bearer " + token.access_token // 请求头带上token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(response => {
  // console.log(response.data,'===222=')
  if (response.data && (response.data.code === 500 || /^[A-Z]\d{4}$/.test(response.data.code))) {
    Message({
      message: response.data.msg,
      type: 'error',
    });
  }
  // else if (response.data && response.data.status == '4446') {
  //   otime_s = 1;
  //   setTimeout(function () {
  //     otime_s = 0;
  //     router.push('/login')
  //   }, 300)
  // }
  return response.data
},
  error => {
    // if (error.indexOf('401')) {
    //   Message({
    //     message: '存在无权限接口',
    //     type: 'error',
    //     duration: 3 * 1000
    //   });
    // } else {
    //   Message({
    //     message: error,
    //     type: 'error',
    //     duration: 3 * 1000
    //   });
    // }
    return Promise.reject(error)
  }
)
//图片验证码地址
service.captchaPath = (params) => {
  return BASE_API + "/authentication/verifiCode/getVerifiCode?uuid=" + params;
}

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
service.tmpUrl = () => {
  return BASE_API + "/filestore/fileStore/uploadReportFile"
}

service.adornUrl = (actionName) => {
  return BASE_API + actionName
}

service.uploadUrl = () => {
  return BASE_API + "/system/file/upload";
}

service.modifyUrl = () => {
  return BASE_API + "/system/pic/update";
}

//充电桩
service.importExcelStakeUrl = () => {
  return BASE_API + "/property/stake/importExcel"
};
//充电枪
service.importExcelConnUrl = () => {
  return BASE_API + "/property/connector/importExcel"
};
// 储能电池
service.importExcelBatUrl = () => {
  return BASE_API + "/property/assetEsbat/importExcel"
};
// 储能设备
service.importExcelEsUrl = () => {
  return BASE_API + "/property/assetEs/importExcel"
};
// 园区
service.importExcelZoneUrl = () => {
  return BASE_API + "/property/zone/importExcel"
};
// 线路管理
service.importExcelLineUrl = () => {
  return BASE_API + "/property/assetLine/importExcel"
};
// 光伏
service.importExcelPvUrl = () => {
  return BASE_API + "/property/assetPv/importExcel"
};
// 站点
service.importExcelStationUrl = () => {
  return BASE_API + "/property/station/importExcel"
};
// 台区
service.importExcelAreaUrl = () => {
  return BASE_API + "/property/assetArea/importExcel"
};
// 配变
service.importExcelTransUrl = () => {
  return BASE_API + "/property/assetTrans/importExcel"
};

// 百度热力图
service.baiduUrl = () => {
  return BASE_API + "/t3/selectOrder"
};

//车辆
service.importExcelEvUrl = () => {
  return BASE_API + "/property/assetEv/importExcel"
};
//车辆导入Eacel验证
service.checkImportExcel = () => {
  return BASE_API + "/property/assetEv/checkImportExcel"
};
// 通用下载方法
export function download (url, params, filename) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  let token = JSON.parse(window.sessionStorage.getItem('user'))
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],

    headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': "Bearer " + token.access_token },
    responseType: 'blob'
  }).then(async (data) => {
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  })
}

export default service
